<?php
namespace Admin\Controller;

use Think\Controller;

//常用函数，可不用实例化，直接调用
class MycommonController extends Controller
{

    const oss_appid = 'LTAIJa93ZFQNlhwY'; //OSS的APPID
    const oss_secret = '3IIq2nm39TDT433BSkaFvG0LxpT5W8'; //OSS的APP_SECRET
    const oss_url = 'http://xycshop.oss-cn-hangzhou.aliyuncs.com';  //OSS的服务器地址
    const oss_bucket = 'xycshop';  //OSS的bucket
    const oss_file = 'xyc';  //OSS的文件夹路径
    const gd_api = '2bb62ea68d917d6882ca854882c89414';  //高德地图web服务api
    const jg_api='19e30bd4929dbb6d59f94c2b';//极光推送api
    const jg_secret='07aabf8c871cb2603fe4bf28';//极光推送secret
    const SMS_ACCOUNT='N3075640';//道森坦利创蓝短信账号， 'N3123345';江域云账号
    const SMS_PASSWORD='C8gWliKHwneaf5';//道森坦利创蓝短信账号密码，'kgXLcAbxfza03e';江域云密码
    static $redis='';
    static $arr=array();//用于存储递归

    /**
     * @param array $eq 查询等式的参数
     * @param array $search 搜索时的匹配参数
     * @param string $time 搜索时间参数
     * @return string $like 模糊查询字段，默认匹配左前缀
     */
    static function set_where($eq = array(), $search = array(), $time = '', $like = array(), $type = false)
    {
        $where = array();
        //等式查询
        if (!empty($eq)) {
            foreach ($eq as $k => $v) {
                $param = strpos($v, '.') !== false ? explode('.', $v)['1'] : $v;
                if (!empty(I($param)) || I($param) === 0) {
                    $where[$v] = I($param);
                }
            }
        }

        //搜查查询
        if (!empty(I('content'))) {
            add_control_log($_SESSION['shop_identifier'],$_SESSION['name'],'搜索内容：'.I('content'),'2');
            $s = '';
            $l = '';
            $find = I('content');
            if (!empty($search)) {
                foreach ($search as $key => $value) {
                    $s .= "{$value}='$find' or ";
                }
            }
            //模糊查询
            if (!empty($like)) {
                foreach ($like as $k => $v) {
                    if ($type == false) {
                        $l .= "$v like '$find%' or ";
                    } else {
                        $l .= "$v like '%$find%' or ";
                    }
                }
            }
            $where['_string'] = rtrim($s . $l, ' or ');
        }

        //时间查询
        if (!empty(I('start')) && !empty(I('end'))) {
            $start = strtotime(I('start'));
            $end = strtotime(I('end') . ' 23:59:59');
            $where[$time] = array('between', array($start, $end));
        } elseif (!empty(I('start') || !empty(I('end')))) {
            if (!empty(I('start'))) {
                $where[$time] = array('egt', strtotime(I('start')));
            } else {
                $where[$time] = array('elt', strtotime(I('end') . ' 23:59:59'));
            }
        }
        return $where;
    }

    /**
     * 设置排序
     * @param string $default 默认排序字段，例如：id asc
     * @param array $orders ，排序字段，1表示升序，2表示降序
     */
    static function order_by($default, $orders)
    {
        if (!empty($orders)) {
            foreach ($orders as $k => $v) {
                $param = strpos($v, '.') !== false ? explode('.', $v)['1'] : $v;
                if (!empty(I($param))) {
                    $order = I($param) == 1 ? $v . ' asc' : $v . ' desc';
                }
            }
            if (empty($order)) {
                $order = $default;
            }
        } else {
            $order = $default;
        }
        return $order;
    }

    /**
     * 检测数组里的某个值是否为空
     * @param array $arr
     */
    static function check_empty($arr)
    {
        foreach ($arr as $k => $v) {
            if (empty($v)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 获取所有下一级
     * @param array $arr 总的数组
     * @param string $current 当前用户码
     * @param string $param 参数，$param[0]为当前用户码参数名，$param[1]为上一级用户码参数名
     * @return array|bool
     */
    static function get_all_next($arr,$current,$param){
        if(empty($current)){
            return false;
        }
        foreach($arr as $k=>$v){
            if($v[$param['1']]==$current){
                self::$arr[]=$v[$param['0']];
                self::get_all_next($arr,$v[$param['0']],$param);
            }
        }
        return self::$arr;
    }

    static function mk_redis(){
        if(empty(self::$redis)){
            self::$redis=new \Redis();
            self::$redis->pconnect(C('REDIS_HOST'), 6379);
            self::$redis->auth(C('REDIS_PWD'));
        }
        return self::$redis;
    }

    /**
     * @param string $title 推送标题
     * @param string $content 推送内容
     * @param string $vid 用户vid
     * @throws \Service\JPush\InvalidArgumentException极光推送
     */

    static function mypush($content, $vid = '', $title = '系统信息', $type = '')
    {
        if (empty($type) || $type == 'android') {
            if(!empty($vid)){
                    $client = new \Service\JPush\Client(self::jg_api, self::jg_secret);//安卓【共享现金】
                $result = $client
                    ->push()
                    ->setPlatform(array('android', 'ios'))
                    ->options(['apns_production' => true]); //options参数，true表示生产环境，默认开发环境，该参数主要针对ios
                //vid为空的话表示群发
                $result->addAlias(trim($vid));
                //ios端是没有标题的，只有安卓端才有标题
                $res = $result
                    ->iosNotification($content, [
                        'sound' => 'sound',
                        'badge' => '+1',
                        'extras' => [
                            'key' => 'value'
                        ]
                    ])
                    ->androidNotification($content, [
                        'title' => $title,
                        'extras' => [
                            'key' => 'value'
                        ]
                    ])
                    ->send();
            } else{
                //一般情况下，安卓和IOS使用同一个api和secret【共享现金】
                $client = new \Service\JPush\Client(self::jg_api, self::jg_secret);//安卓
                $result = $client
                    ->push()
                    ->setPlatform(array('android', 'ios'))
                    ->options(['apns_production' => true]); //options参数，true表示生产环境，默认开发环境，该参数主要针对ios
                //vid为空的话表示群发
                $result->addAllAudience();
                //ios端是没有标题的，只有安卓端才有标题
                $res = $result
                    ->iosNotification($content, [
                        'sound' => 'sound',
                        'badge' => '+1',
                        'extras' => [
                            'key' => 'value'
                        ]
                    ])
                    ->androidNotification($content, [
                        'title' => $title,
                        'extras' => [
                            'key' => 'value'
                        ]
                    ])
                    ->send();
            }
        }
    }


    /**
     * 趣消费极光推送
     * @param string $title 推送标题
     * @param string $content 推送内容
     * @param string $vid 用户vid
     * @throws \Service\JPush\InvalidArgumentException极光推送
     */
    static function qxf_push($content, $id = '', $title = '系统信息', $type = '',$app_id,$app_secret)
    {
        if (empty($type) || $type == 'android') {
            if(!empty($id)){
                $client = new \Service\JPush\Client($app_id, $app_secret);//安卓【趣消费】
//
                $result = $client
                    ->push()
                    ->setPlatform(array('android', 'ios'))
                    ->options(['apns_production' => false]); //options参数，true表示生产环境，默认开发环境，该参数主要针对ios
                //vid为空的话表示群发

                $result->addAlias(trim($id));
//                return $result;
                //ios端是没有标题的，只有安卓端才有标题
                $res = $result->setNotificationAlert($content)->send();
//                    ->iosNotification($content, [
//                        'sound' => 'sound',
//                        'badge' => '+1',
//                        'extras' => [
//                            'key' => 'value'
//                        ]
//                    ])
//                    ->androidNotification($content, [
//                        'title' => $title,
//                        'extras' => [
//                            'key' => 'value'
//                        ]
//                    ])
//                    ->send();

            } else{
                //一般情况下，安卓和IOS使用同一个api和secret【共享现金】
                $client = new \Service\JPush\Client($app_id, $app_secret);//安卓
                $result = $client
                    ->push()
                    ->setPlatform(array('android', 'ios'))
                    ->options(['apns_production' => true]); //options参数，true表示生产环境，默认开发环境，该参数主要针对ios
                //vid为空的话表示群发
                $result->addAllAudience();
                //ios端是没有标题的，只有安卓端才有标题
                $res = $result
                    ->iosNotification($content, [
                        'sound' => 'sound',
                        'badge' => '+1',
                        'extras' => [
                            'key' => 'value'
                        ]
                    ])
                    ->androidNotification($content, [
                        'title' => $title,
                        'extras' => [
                            'key' => 'value'
                        ]
                    ])
                    ->send();
            }
            return $res;
        }
    }

    /**
     * 创蓝短信平台
     * @param string $mobile 手机号
     * @param string $content 内容
     */
    static function cl_sms1($mobile, $content,$sign='信用查')
    {
        date_default_timezone_set('PRC');//设置时区
        $url = 'https://smssh1.253.com/msg/send/json';
        $qianming='【信用查】';
        $data['account'] = self::SMS_ACCOUNT;//道森坦利账号
        $data['password'] = self::SMS_PASSWORD;//道森坦利密码
        $data['msg'] = $qianming . $content;
        $data['phone'] = $mobile;
        $data['sendtime'] = date('YmdHi');
        $data['report'] = 'true';
        $header = array('Content-Type:application/json;charset=utf-8');
        $result = self::set_curl($url, json_encode($data), $header);
        $res = json_decode($result, true);
        if ($res['code'] == '0') {
            return true;
        } else {
            return $res['errorMsg'];
        }
    }
    static function cl_sms($mobile, $content,$sign='信用查')
    {
        date_default_timezone_set('PRC');//设置时区
        $url = 'http://adm.jyyjrfw.com/External/external_send_sms';
        $data['app']='【'.$sign.'】';
        $data['content'] = $content;
        $data['mobile'] = $mobile;
        $result = self::set_curl($url,$data);
        $res = json_decode($result, true);
        if ($res['code'] == '1001') {
            return true;
        } else {
            return $res['result'];
        }
    }

    /**
     * 通过经纬度获取具体地址
     * 例如lat:40.771454,lon:107.407763
     */
    static function get_address($lat, $lon)
    {
        $url = 'http://restapi.amap.com/v3/geocode/regeo?key=' . self::gd_api . '&location=' . $lon . ',' . $lat;
        $res = self::set_curl($url);
        $res = json_decode($res, true);
        return $res['regeocode']['formatted_address'];
    }

    static function getAddressByIp($ip){
        $url='http://ip.taobao.com/service/getIpInfo.php?ip='.$ip;
        return self::set_curl($url);
    }

    /**
     * *
     * 导出指定时间的已分派数据
     * @param array $letter 字母
     * @param array $field 数据库字段名
     * @param array $param 字段对应注释
     * @param array $list 查询出来的列表 二维数组
     * @param array $special_param 需要特殊处理的参数 例如 array('status'=>array('1,2,3'=>'未付款,已付款,已删除'))，表示status有1、2、3三种状态对应三种注释
     */
    static function down_data($letter, $field, $param, $list, $special_param = array())
    {
        $letter = range(strtoupper($letter[0]), strtoupper($letter[1]));
        if (count($letter) != count($field) || count($param) != count($field) || count($letter) != count($param)) {
            return false;
//            self::ajax('1002','参数数量有误','error');
        }
        //用户名、手机号、身份证、地址、还款订单、还款金额、应还款时间、逾期天数、罚金、分派人员
        require_once './Public/excel/PHPExcel.php'; //导入php文件
        $filePath = './Public/excel/record/record.xlsx'; //打开excel路径
        $PHPReader = new \PHPExcel_Reader_Excel2007(); //默认用excel2007读取excel
        $PHPExcel = $PHPReader->load($filePath); //加载具体文件
        $PHPExcel->setActiveSheetIndex(0);
        //用户名、手机号、身份证、地址、还款订单、还款金额、应还款时间、逾期天数、罚金、分派人员
        foreach ($letter as $k => $v) {
            $PHPExcel->getActiveSheet()->setCellValue($v . '1', $param[$k]);//写入
        }
        $num = 2;
        foreach ($list as $key => $value) {

            foreach ($field as $k => $v) {
                $PHPExcel->getActiveSheet()->setCellValue($letter[$k] . $num, $value[$v]);//写入
            }
            $num++;
//            $PHPExcel->getActiveSheet()->setCellValue('A' . $num, $value['truename']);//写入
        }
        $objWriter = \PHPExcel_IOFactory::createWriter($PHPExcel, 'Excel2007');//保存类型
        $name = date('YmdHis', time()) . rand('10', '99') . '.xlsx';
        $objWriter->save('./Public/excel/record/' . $name);
        if (file_exists('./Public/excel/record/' . $name)) {
            add_down_data_log($_SESSION['id'],'导出数据字段：'.json_encode($field,JSON_UNESCAPED_UNICODE));
            $url = C('MYURL') . 'Public/excel/record/' . $name;
            $url=self::addossimg('./Public/excel/record/' . $name);
            unlink('./Public/excel/record/' . $name);
            return $url;
        } else {
            return false;
        }
    }

    /**
     * 导入数据，返回读取到的数据，以二维数组返回
     * @param array $file 上传文件，比如$_FILES['data']
     * @param array $fields 数据表字段
     * @return array|string
     */
    static function import_data($file,$fields=['mobile']){
        if($file['error']=='4'){
            return '请选择excel文件上传';
//            $this->error('请选择excel文件上传');
//            exit();
        }
        $arr=array_combine(range(1,26),range('A','Z'));
        header("content-type:text/html;charset=utf-8");
        require_once './Public/excel/PHPExcel.php'; //导入php文件
        $config = array(
            'rootPath' => './Public/excel/import_record/',   //上传根目录
            'maxSize' => 1024*1024*10,   //允许文件10M大小
            'exts' => array('xlsx', 'xls','csv'),     //允许文件后缀,以逗号隔开
        );
        $upload=new \Think\Upload($config);
//        $res=$upload->uploadOne($_FILES['data']);
        $res=$upload->uploadOne($file);
        if($res){
            //文件保存路径
            $url=$upload->rootPath.$res['savepath'].$res['savename'];
        }else{
            return $upload->getError();
        }
        $filePath = $url;
        //默认用excel2007读取excel，若格式不对，则用之前的版本进行读取
        $PHPReader = new \PHPExcel_Reader_Excel2007();
        if (!$PHPReader->canRead($filePath)) {
            $PHPReader = new \PHPExcel_Reader_Excel5();
            if (!$PHPReader->canRead($filePath)) {
                return '数据读取失败';
//                $this->error('数据读取失败');
            }
        }
        //读取Excel文件
        $PHPExcel = $PHPReader->load($filePath);
        //读取excel文件中的第一个工作表
        $sheet = $PHPExcel->getSheet(0);
        //取得最大的列号
        $allColumn = $sheet->getHighestColumn();
        //取得最大的行号
        $allRow = $sheet->getHighestRow();

        $field=count($fields);//获取字段数量
        $letter=range('A',$arr[$field]);//数量对应的字母
        //从第二行开始插入,第一行是列名
        for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
            foreach($letter as $k=>$v){
                $$v=$PHPExcel->getActiveSheet()->getCell($v . $currentRow)->getValue();
                if($$v!==null){
                    $data[$fields[$k]]=$$v;
                }
            }
            if(!empty($data)){
                $datas[]=$data;
            }
            //获取A列的值
//            $A = $PHPExcel->getActiveSheet()->getCell("A" . $currentRow)->getValue();
//            if($A!=''){
//                $data['mobile']=$A;
//                $datas[]=$data;
//            }
        }
        if(!empty($datas)){
            if($res){
                unlink($url);
                rmdir('./Public/excel/import_record/'.date('Y-m-d',time()));
                return $datas;
            }else{
                return '导入失败';
            }
        }else{
            return '导入失败，数据不能为空';
        }
    }

    /**
     * 生成二维码
     * @param string $url 链接
     * @param string $name 文件名
     * @return string
     */
    static function get_qrcode($url, $name)
    {
        $level = 'H';
        //二维码保存路劲
        $code = new \Service\Qrcode();
        $name = $name . '_' . time() . '.jpg';
        $code::png($url, './Public/' . $name, $level);
        $url=self::addossimg('./Public/'.$name);
//        return C('MYURL') . 'Public/' . $name;
        return $url;
    }

    /**
     * @param string $url 上传地址
     * @param array $data 上传数组
     * @param string $header 头文件设置
     */
    static function set_curl($url, $data = array(), $header = '')
    {
        $ch = curl_init();
        if (!empty($header)) {
//            $header=array('Content-type: application/json','charset:utf-8'); 示例
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, '1');
        curl_setopt($ch, CURLOPT_URL, $url);
        if (!empty($data)) {
            curl_setopt($ch, CURLOPT_POST, '1');
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        //禁用后cURL将终止从服务端进行验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $res = curl_exec($ch);
        if (curl_error($ch)) {
            return '错误信息:' . curl_error($ch);
        }
        curl_close($ch);
        return $res;
    }

    /**
     * 用于图片下载放到服务器端，然后再上传到oss端
     * @param string $url 图片地址
     * @param bool $name 默认true表示使用原文件名，false则是随机生成文件名
     */
    static function img_curl($url, $name = true)
    {
        $ch = curl_init();
        if ($name == false) {
            $file_path = './Public/down_img/' . pathinfo($url, PATHINFO_BASENAME);
        } else {
            $file_path = './Public/down_img/' . time() . rand(100, 999) . '.' . pathinfo($url, PATHINFO_EXTENSION);
        }
        $f = fopen($file_path, 'w'); //需要给文件夹附权限，否则可能失败
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, '1');
        curl_setopt($ch, CURLOPT_URL, $url);
        //禁用后cURL将终止从服务端进行验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_FILE, $f);
        $res = curl_exec($ch);
        $img_info = curl_getinfo($ch);
        if ($img_info['size_download'] != filesize($file_path)) {
            self::ajax('1002', '下载失败', 'error');
        }
        if (curl_error($ch)) {
            self::ajax('1002', curl_error($ch), 'error');
        }
        curl_close($ch);
        fclose($f);
        self::ajax('1001', '下载成功', 'error');
    }

    /**
     *单图片上传
     * @param string $name input标签name值
     */
    static function uploadimg($name,$custom_name='')
    {
        if (!empty($_FILES)) {
            $config = array(
                'maxSize' => 0, //上传的文件大小限制 (0-不做限制)
                'exts' => array('jpg', 'jpeg', 'png'), //允许上传的文件后缀
                'rootPath' => './Public/upload/' //保存根路径
            );
            $upload = new \Think\Upload($config);
            $res = $upload->uploadOne($_FILES[$name]);
            if ($res) {
                $url = self::addossimg($upload->rootPath . $res['savepath'] . $res['savename'],$custom_name);
                if ($url) {
                    unlink($upload->rootPath . $res['savepath'] . $res['savename']); //删除文件
                    rmdir($upload->rootPath . date('Y-m-d', time()));  //删除文件所在文件夹
                    self::ajax('1001', $url);
                } else {
                    self::ajax('1002', '上传失败', 'error');
                }
            } else {
                self::ajax('1002', $upload->getError(), 'error');
            }
        }
    }

    /**
     * 编辑器图片上传
     * @param string $filekey 自定义的key值
     */
    static function editor_upload($filekey)
    {
        $config = array(
            'exts' => array('jpg', 'jpeg', 'png', 'gif', 'ico'), //允许上传的文件后缀
            'rootPath' => './Public/upload/', //保存根路径
        );
        $upload = new \Think\Upload($config);
        $img = $upload->uploadOne($_FILES[$filekey]);
        if ($img) {
            $url = self::addossimg($upload->rootPath . $img['savepath'] . $img['savename']);
            if ($url) {
                unlink($upload->rootPath . $img['savepath'] . $img['savename']); //删除文件
                rmdir($upload->rootPath . date('Y-m-d', time()));  //删除文件所在文件夹
                echo json_encode(['success' => 'true', 'msg' => '上传成功', 'file_path' => $url]);  //编辑器要求返回格式
            } else {
                echo json_encode(['success' => 'false', 'msg' => '上传失败']);
            }
        } else {
            echo json_encode(['success' => 'false', 'msg' => '上传失败']);
        }
    }

    /**
     * @param string $image 文件路径 比如./Public/test.jpg
     * @return string
     */
    static function addossimg($image,$custom_name='')
    {
        //引入OSS类文件
        $success = new \Service\OssClient(self::oss_appid, self::oss_secret, self::oss_url);
        $ext = pathinfo($image, PATHINFO_EXTENSION);
        if(empty($custom_name)){
            $img_name = time() . uniqid() . '.' . $ext;
        }else{
            $img_name = time() . uniqid() .$custom_name. '.' . $ext;
        }

        //先在oss上建一个图片存放容器，lingsui为上传路径
        $object = self::oss_file . '/' . $img_name;
        try {
            //ceshimain为bucket，即存放文件的区域，必备，区域只能有一个，但区域下面可以建多个文件夹，比如上面的lingsui文件夹
            $success->uploadFile(self::oss_bucket, $object, $image);
            //最后返回图片地址
            return self::oss_url . '/' . self::oss_file . '/' . $img_name;
        } catch (Exception $e) {
            printf(__FUNCTION__ . ": FAILED\n");
            printf($e->getMessage() . "\n");
            return false;
        }
    }

    /**
     * 多图片上传
     */
    public function many_uploadimg()
    {
        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        header("Cache-Control: no-store, no-cache, must-revalidate");
        header("Cache-Control: post-check=0, pre-check=0", false);
        header("Pragma: no-cache");


// Support CORS
// header("Access-Control-Allow-Origin: *");
// other CORS headers if any...
        if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
            exit; // finish preflight CORS requests here
        }

        if (!empty($_REQUEST['debug'])) {
            $random = rand(0, intval($_REQUEST['debug']));
            if ($random === 0) {
                header("HTTP/1.0 500 Internal Server Error");
                exit;
            }
        }

// header("HTTP/1.0 500 Internal Server Error");
// exit;


// 5 minutes execution time
        @set_time_limit(5 * 60);

// Uncomment this one to fake upload time
        usleep(5000);

// Settings
// $targetDir = ini_get("upload_tmp_dir") . DIRECTORY_SEPARATOR . "plupload";
        $targetDir = './Public/many_uploadimg/upload_tmp';
        $uploadDir = './Public/many_uploadimg/upload';

        $cleanupTargetDir = true; // Remove old files
        $maxFileAge = 5 * 3600; // Temp file age in seconds


// Create target dir
        if (!file_exists($targetDir)) {
            @mkdir($targetDir);
        }

// Create target dir
        if (!file_exists($uploadDir)) {
            @mkdir($uploadDir);
        }

// Get a file name
        if (isset($_REQUEST["name"])) {
            $fileName = time() . rand(100, 999) . '.' . pathinfo($_REQUEST["name"], PATHINFO_EXTENSION);
        } elseif (!empty($_FILES)) {
            $fileName = time() . rand(100, 999) . '.' . pathinfo($_FILES["file"]["name"], PATHINFO_EXTENSION);
        } else {
            $fileName = uniqid("file_");
        }

        $md5File = @file('md5list.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        $md5File = $md5File ? $md5File : array();

        if (isset($_REQUEST["md5"]) && array_search($_REQUEST["md5"], $md5File) !== FALSE) {
            die('{"jsonrpc" : "2.0", "result" : null, "id" : "id", "exist": 1}');
        }

        $filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;
        $uploadPath = $uploadDir . DIRECTORY_SEPARATOR . $fileName;

// Chunking might be enabled
        $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
        $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 1;


// Remove old temp files
        if ($cleanupTargetDir) {
            if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
            }

            while (($file = readdir($dir)) !== false) {
                $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;

                // If temp file is current file proceed to the next
                if ($tmpfilePath == "{$filePath}_{$chunk}.part" || $tmpfilePath == "{$filePath}_{$chunk}.parttmp") {
                    continue;
                }

                // Remove temp file if it is older than the max age and is not the current file
                if (preg_match('/\.(part|parttmp)$/', $file) && (@filemtime($tmpfilePath) < time() - $maxFileAge)) {
                    @unlink($tmpfilePath);
                }
            }
            closedir($dir);
        }


// Open temp file
        if (!$out = @fopen("{$filePath}_{$chunk}.parttmp", "wb")) {
            die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
        }

        if (!empty($_FILES)) {
            if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
            }

            // Read binary input stream and append it to temp file
            if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
            }
        } else {
            if (!$in = @fopen("php://input", "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
            }
        }

        while ($buff = fread($in, 4096)) {
            fwrite($out, $buff);
        }

        @fclose($out);
        @fclose($in);

        rename("{$filePath}_{$chunk}.parttmp", "{$filePath}_{$chunk}.part");

        $index = 0;
        $done = true;
        for ($index = 0; $index < $chunks; $index++) {
            if (!file_exists("{$filePath}_{$index}.part")) {
                $done = false;
                break;
            }
        }
        if ($done) {
            if (!$out = @fopen($uploadPath, "wb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
            }

            if (flock($out, LOCK_EX)) {
                for ($index = 0; $index < $chunks; $index++) {
                    if (!$in = @fopen("{$filePath}_{$index}.part", "rb")) {
                        break;
                    }

                    while ($buff = fread($in, 4096)) {
                        fwrite($out, $buff);
                    }

                    @fclose($in);
                    @unlink("{$filePath}_{$index}.part");
                }

                flock($out, LOCK_UN);
            }
            @fclose($out);
        }

        $url = self::addossimg($uploadPath);
        if ($url) {
            self::ajax('1001', $url);
        } else {
            self::ajax('1002', '上传失败', 'error');
        }
//        $uploadPath=C('MYURL').ltrim($uploadPath,'./');
//        die('{"jsonrpc" : "2.0", "error" : {"code": 1, "message": '.$uploadPath.'}, "id" : "id"}');
//        echo json_encode(['code'=>'1001','result'=>$uploadPath]);
    }


    /**
     * @param string $code 错误码 1001成功 1002失败
     * @param string $result 详细信息
     * @param string $r 为error的时候表示返回错误信息
     * @return bool
     */
    static function ajax($code, $result, $error = '')
    {
        if (empty($error) || $code == '1001') {
            parent::ajaxReturn(['code' => $code, 'result' => $result]);
        } else {
            parent::ajaxReturn(['code' => $code, 'result' => $result]);
            exit();
        }
    }

    /**
     * 生成订单号
     */
    static function build_orderno()
    {
        $time = explode(' ', microtime());
        $time2 = substr($time['0'], '2', '-2');
        return date('YmdHis', time()) . $time2 . rand(1, 9).'ra';
    }

    public function _empty()
    {
        $this->redirect('Alerterror/error404');
    }

    /**
     * 将一个字符串部分字符用$re替代隐藏
     * @param string    $string   待处理的字符串
     * @param int       $start    规定在字符串的何处开始，
     *                            正数 - 在字符串的指定位置开始
     *                            负数 - 在从字符串结尾的指定位置开始
     *                            0 - 在字符串中的第一个字符处开始
     * @param int       $length   可选。规定要隐藏的字符串长度。默认是直到字符串的结尾。
     *                            正数 - 从 start 参数所在的位置隐藏
     *                            负数 - 从字符串末端隐藏
     * @param string    $re       替代符
     * @return string   处理后的字符串
     */
    static function hidestr($string, $start = 0, $length = 0, $re = '*') {
        if (empty($string)) return false;
        $strarr = array();
        $mb_strlen = mb_strlen($string);
        while ($mb_strlen) {//循环把字符串变为数组
            $strarr[] = mb_substr($string, 0, 1, 'utf8');
            $string = mb_substr($string, 1, $mb_strlen, 'utf8');
            $mb_strlen = mb_strlen($string);
        }
        $strlen = count($strarr);
        $begin  = $start >= 0 ? $start : ($strlen - abs($start));
        $end    = $last   = $strlen - 1;
        if ($length > 0) {
            $end  = $begin + $length - 1;
        } elseif ($length < 0) {
            $end -= abs($length);
        }
        for ($i=$begin; $i<=$end; $i++) {
            $strarr[$i] = $re;
        }
        if ($begin >= $end || $begin >= $last || $end > $last) return false;
        return implode('', $strarr);
    }


}